var mongoose = require('mongoose');
const Content = require('../models/content.model');

exports.create = function(req,res,next){
	const content = new Content(req.body);

	content.save()
	.then(data=>{
		res.json(data);
	})
}

exports.get = function(req,res,next){
	var id = req.params.id;

	Content.findById(id, function (err, data) {
	  res.json(data);
	})
}


exports.update = function(req,res,next){
	const id = req.params.id;

	Content.findByIdAndUpdate(id, {$set: req.body}, {new:false})
	.then(data=>{
		res.json(data); //修改前是的数据
	})

}

exports.remove = function(req,res,next){
	const id = req.params.id;

	Content.findByIdAndRemove(id,function(err,data){
		res.json(data);
	})
	
}


exports.list = function(req,res,next){
	var page = (req.body.page) ? req.body.page : 1;
	var rows = (req.body.rows) ? req.body.rows : 5;

	var cateId=(req.body.cateId)?req.body.cateId:null;
	var value=(req.body.value)?req.body.value:null;
	
	var queryCondition = {};
	
	if(cateId){
		queryCondition={
			"cateId":cateId,
		}
	}
	
	Content.paginate(queryCondition, {sort:{_id:1}, page: parseInt(page), limit: parseInt(rows) }, function(err, result) {
		//评论数获取参考代码
//		async.map(result.docs,function(news,done){
//			Com.count({contentId:content._id},function(err,count){
//				if(err){
//					done(err);
//				}else{
//					content.comCount=count;
//					done(null,content);
//				}
//			})
//		}),function(err){
//			if(err){
//				return;
//			}else{
//				res.json(result);
//			}
//		}
	 	result.rows = result.docs;
	 	delete result.docs;
	 	res.json(result)
	});
	
}

exports.deletes= function(req,res,next){
	var ids=req.body.ids;
	if(ids.length>0){
		Content.remove({_id:{$in:ids.split(',')}})
		.then(data=>{
			res.json({'msg':'deletes success','status':200})
		});
	}else{
		res.json({'msg':'deletes fail','status':404})
	}
}